<?php

namespace App\Models\Knowledge;

use App\Models\Flaw\Category;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;

class Knowledge extends Model
{
    protected $table = 'knowledge';

    protected $primaryKey = 'id';

    protected $fillable = [];

    protected $guarded = [];

    public $timestamps = true;


    public function rules ($request){
        // dd($request->id);
        return [
            'title'       => ['required',Rule::unique($this->table)->ignore($request->id)],
            'category_id' => 'required',
            'content'     => 'required'
        ];
    }

    public function messages (){
        return [
            'title.required'       => '请填写标题',
            'title.unique'         => '标题已存在',
            'category_id.required' => '请选择分类',
            'content.required'     => '请填写内容'
        ];
    }

    public function validate ($request){
        return Validator::make($request->all(),
            $this->rules($request),
            $this->messages()
        );
    }

    /**
     * 新建文章
     * @param $request
     * @throws \Exception
     * @return bool
     */
    public function store ($request){
        $data = $request->all();
        $data['klg_number']    = $this->generateNumber();
        $data['category_id']   = implode(',',$data['category_id']);
        $data['user_id']       = Auth::user()->id;
        $data['content'] = clean($request->content, 'user_topic_body');
        $id = $this->create($data)->id;
        if ($id <= 0){
            throw new \Exception('文章发布失败');
        }
        return true;
    }

    /**
     * 生成文章编号
     */
    private function generateNumber (){

        return 'knowledge-' . ($this->count() + 1);
    }

    /**
     * 查询列表
     * @param $sel
     * @param $where
     * @param $limit
     * @return mixed
     */
    public function lists ($sel,$where,$limit){

        $builder = $this->select($sel);
        $builder = $builder->leftjoin('users', 'knowledge.user_id', '=', 'users.id');
        $builder = $builder->when(isset($where['category_id']) && $where['category_id']>0,function($query) use ($where){
                return $query->where($this->table.'.category_id','like','%'. $where['category_id'] .'%');
            })->when(isset($where['keywords']) && !empty($where['keywords']),function($query) use ($where){
                return $query->where($this->table.'.title','like','%'.$where['keywords'].'%')->orwhere($this->table.'.content','like','%'.$where['keywords'].'%');
            });
        $count = $builder->count();
        $list =$builder->offset($limit[0])->limit($limit[1])->orderBy($this->table.'.created_at','DESC')->get();
        foreach ($list as $item){
            //多个分类
            $categories = Category::select('name')->whereIn('id',explode(',',$item->category_id))->get();
            $item->categories = $categories->implode('name',',');
        }
        return ['count'=>$count,'list'=>$list];
    }

    /**
     * 更新文章浏览量
     * @return bool
     */
    public function updateViews (){

        ++$this->views;

        return $this->save();
    }

    /**
     * 新建文章
     * @param $request
     * @throws \Exception
     * @return bool
     */
    public function updateRow ($request){
        $klg = $this->find($request->id);
        $klg->title = $request->title;
        $klg->content = clean($request->content, 'user_topic_body');

        $klg->category_id   = implode(',',$request->category_id);
        // $klg->user_id       = Auth::user()->id;

        if (!$klg->save()){
            throw new \Exception('文章更新失败');
        }
        return true;
    }

}
